package cn.lili.task;

import cn.lili.modules.payment.kit.plugin.wechat.WechatV3Api;
import cn.lili.modules.store.entity.dos.StoreSft;
import cn.lili.modules.store.service.StoreSftService;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.jfinal.kit.Ret;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.List;

@Configuration
@EnableScheduling
@Slf4j
public class StoreSftTask {
    @Autowired
    private StoreSftService storeSftService;

    @Scheduled(cron = "0 0/2 * * * ?")
    public void a() {
        List<StoreSft> list = storeSftService.findAudit();
        log.info("....收付通任务调度");
        if (CollectionUtils.isNotEmpty(list)) {

            for (StoreSft storeSft : list) {
                try {
                    Ret ret = WechatV3Api.getApplyment(storeSft.getApplymentId(), storeSft.getStoreId());

                    if (ret.isOk()) {

                        storeSft.setStatus(ret.getStr("applyment_state"));
                        storeSft.setStatusDesc(ret.getStr("applyment_state_desc"));
                        storeSft.setSignState(ret.getStr("sign_state"));
                        storeSft.setSignUrl(ret.getStr("sign_url"));
                        storeSft.setSubMchid(ret.getStr("sub_mchid"));
                        JSONObject accountValidation = ret.getAs("account_validation");
                        if (accountValidation != null) {
                            accountValidation.put("account_name", WechatV3Api.decrypt(accountValidation.getString("account_name")));
                            accountValidation.put("account_no", WechatV3Api.decrypt(accountValidation.getString("account_no")));
                            storeSft.setAccountValidation(JSON.toJSONString(accountValidation));
                        } else {
                            storeSft.setAccountValidation("{}");
                        }
                        storeSft.setAuditDetail(JSON.toJSONString(ret.get("audit_detail")));
                        storeSft.setLegalValidationUrl(ret.getStr("legal_validation_url"));
                        storeSft.setApplymentId(ret.getStr("applyment_id"));

                        storeSftService.updateById(storeSft);
                    }
                } catch (Exception e) {
                    log.error(storeSft.getStoreId() + " 收付通检测失败", e);
                }
            }
        }
    }
}
